﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.UI;
using WaterRegimenMonitor.Web.Models;
using WaterRegimenMonitor.Common;
using WaterRegimenMonitor.Web.DataModel;
using WaterRegimenMonitor.Web.Domain;

namespace WaterRegimenMonitor.Web.Controllers
{
    /// <summary>
    /// 用户登陆控制器。
    /// </summary>
    public class LoginController : Controller
    {
        [OutputCache(Location = OutputCacheLocation.None, Duration = 0, VaryByParam = "None")]
        [HandleError(ExceptionType = typeof(Exception), View = "Exception")]
        public new ActionResult User()
        {
            return View();
        }

        [HttpPost, ValidateInput(false)]
        [HandleError(ExceptionType = typeof(Exception), View = "Exception")]
        public new ActionResult User(UserLoginViewModel viewModel)
        {
            //用于保存用户信息
            User user = null;

            //执行登陆操作
            LoginResult result = LoginHelper.Login(viewModel.UserName, viewModel.Password, out user);

            //判断是否登录成功
            if (result == LoginResult.MustChangePassword)
            {
                return RedirectToAction("Confirm", new { userID = user.UserID });
            }

            if (result == LoginResult.Ok)
            {
                Authentication.Login(user.UserID.ToString(), System.Web.HttpContext.Current.Response);
                return RedirectToAction("Index", "Home");
            }

            //设置错误信息
            BuildModelError(result);

            //返回视图
            return View();
        }

        [HttpGet, ValidateInput(false)]
        [HandleError(ExceptionType = typeof(Exception), View = "Exception")]
        public ActionResult Confirm(Guid userID)
        {
            return View(new UserConfirmViewModel(userID));
        }


        [HttpPost, ValidateInput(false)]
        [HandleError(ExceptionType = typeof(Exception), View = "Exception")]
        public ActionResult Confirm(UserConfirmViewModel viewModel)
        {
            //if (ModelState.IsValid)
            //{
            //    UserHelper.ChangePassword(viewModel.UserID, viewModel.Password);
            //    Authentication.Login(viewModel.UserID.ToString(), System.Web.HttpContext.Current.Response);
            //    return RedirectToAction("Index", "Home");
            //}
            //return View(viewModel);
            return null;
        }

        [HttpGet, ValidateInput(false)]
        [HandleError(Order = 3, ExceptionType = typeof(UnauthenticatedException), View = "Unauthenticated")]
        [HandleError(Order = 2, ExceptionType = typeof(UnauthorizedException), View = "Unauthorized")]
        [HandleError(Order = 1, ExceptionType = typeof(Exception), View = "Exception")]
        public ActionResult ChangePassword()
        {
            if (!Helper.IsAuthenticated)
            {
                throw new UnauthenticatedException("您还没有登录，请登录!");
            }

            return View(new ChangePasswordViewModel());
        }

        [HttpPost, ValidateInput(false)]
        [HandleError(Order = 3, ExceptionType = typeof(UnauthenticatedException), View = "Unauthenticated")]
        [HandleError(Order = 2, ExceptionType = typeof(UnauthorizedException), View = "Unauthorized")]
        [HandleError(Order = 1, ExceptionType = typeof(Exception), View = "Exception")]
        public ActionResult ChangePassword(ChangePasswordViewModel viewModel)
        {
            if (!Helper.IsAuthenticated)
            {
                throw new UnauthenticatedException("您还没有登录，请登录!");
            }

            if (ModelState.IsValid)
            {
                UserHelper.ChangePassword(Helper.CurrentPrincipal.User.UserID, viewModel.Password);
                return RedirectToAction("Index", "Home");
            }

            return View(new ChangePasswordViewModel());
        }

        /// <summary>
        /// 生成模型错误信息。
        /// </summary>
        /// <param name="result">The result.</param>
        private void BuildModelError(LoginResult result)
        {
            switch (result)
            {
                case LoginResult.UserDisabled:
                    ModelState.AddModelError("", "此用户已经被禁用!");
                    break;

                case LoginResult.UserPasswordNotMatch:
                    ModelState.AddModelError("", "用户密码错误!");
                    break;

                case LoginResult.UserNotExist:
                    ModelState.AddModelError("", "用户不存在!");
                    break;
            }
        }
    }
}
